import torchvision
import torch
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader

batch_size = 64

# 使用GPU进行训练
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

## 数据集准备阶段

# 将图像转换成张量，以及将图片进行归一化处理
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor(),
                                            torchvision.transforms.Normalize((0.5,), (0.5,))
                                            ])

# 读入数据 注意这边 transform=transform 将图片转换成适用于网络的张量
train_set = torchvision.datasets.MNIST(root='./dataset/MNIST/train', train=True, download=True, transform=transform)

train_loader = DataLoader(train_set, shuffle=True, batch_size=batch_size)

test_set = torchvision.datasets.MNIST(root='./dataset/MNIST/test', train=False, download=True, transform=transform)

test_loader = DataLoader(test_set, shuffle=True, batch_size=batch_size)


## 网络搭建阶段
class Net(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.modal = torch.nn.Sequential(
            # 输入特征 1*28*28
            torch.nn.Conv2d(in_channels=1, out_channels=10, kernel_size=5),
            # 10 * 24 * 24  c从1变成10是由于经过了conv2d层，28*28变成24*24是由于kernel_size为5
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2),
            # 10 * 12 * 12 经过kernel size为2的MaxPooling层时24*24变成12*12
            torch.nn.Conv2d(in_channels=10, out_channels=20, kernel_size=5),
            # 20 * 8 * 8 过程同上
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2),
            # 20 * 4 * 4 过程同上
            torch.nn.Flatten(),
            torch.nn.Linear(in_features=20 * 4 * 4, out_features=10),
            torch.nn.Softmax(dim=1)
        )

    def forward(self, x):
        output = self.modal(x)
        return output

model = Net()
print(model.to(device))

# 构造损失和优化函数
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.5)


# 训练模块
def train(epoch):
    running_loss = 0
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        inputs, target = inputs.to(device), target.to(device)
        optimizer.zero_grad()

        # 前馈+反向传播+更新
        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if batch_idx % 300 == 299:
            print('[%d,%5d] loss:%.3f' % (epoch + 1, batch_idx + 1, running_loss / 2000))
            running_loss = 0.0


def Test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            inputs, target = data
            inputs, target = inputs.to(device), target.to(device)
            outputs = model(inputs)
            _, predicted = torch.max(outputs.data, dim=1)
            total += target.size(0)
            correct += (predicted == target).sum().item()

    print('Accuracy on test set:%d %%[%d/%d]' % (100 * correct / total, correct, total))


if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        Test()
